package com.czh.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.fastjson2.JSON;
import com.czh.gateway.constants.RedisKeyConstant;
import com.czh.gateway.entity.AuthPermission;
import com.czh.gateway.entity.AuthRole;
import com.czh.gateway.redis.RedisUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 自定义权限数据加载
 */
@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取用户的权限集合
     * @param loginId  账号id
     * @param loginType 账号类型
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuth(loginId, RedisKeyConstant.authPermissionPrefix);
    }

    /**
     * 获取当前用户角色集合
     * @param loginId  账号id
     * @param loginType 账号类型
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth(loginId,RedisKeyConstant.authRolePrefix);
    }

    private List<String> getAuth(Object loginId,String prefix){
        String authKey = redisUtil.buildKey(prefix, loginId.toString());
        List<Object> redisList = redisUtil.getCacheList(authKey);
        List<String> authList = Collections.emptyList();
        if (Objects.isNull(redisList)){
            return authList;
        }
        if (prefix.equals(RedisKeyConstant.authRolePrefix)){
            List<AuthRole> roleList = JSON.parseArray(redisList.toString(), AuthRole.class);
            authList = roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
        } else if (prefix.equals(RedisKeyConstant.authPermissionPrefix)) {
            List<AuthPermission> permissionList = JSON.parseArray(redisList.toString(), AuthPermission.class);
            authList = permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        }
        return authList;
    }

}
